package com.jwong.grpc.customheader;

import com.jwong.grpc.helloworld.GreeterGrpc;
import com.jwong.grpc.helloworld.HelloReply;
import com.jwong.grpc.helloworld.HelloRequest;
import io.grpc.*;

import java.util.concurrent.TimeUnit;

public class CustomHeaderClient {

    private final GreeterGrpc.GreeterBlockingStub blockingStub;
    private final ManagedChannel originChannel;

    public CustomHeaderClient(String host, int port) {
        originChannel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();
        ClientInterceptor interceptor = new HeaderClientInterceptor();
        Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    private void shutdown() throws InterruptedException {
        originChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public HelloReply sayHello(String name) {
        return blockingStub.sayHello(
                HelloRequest.newBuilder()
                        .setName(name)
                        .build());
    }

    public static void main(String[] args) throws InterruptedException {
        CustomHeaderClient customHeaderClient = new CustomHeaderClient("localhost", 9000);
        HelloReply helloReply = customHeaderClient.sayHello("WangCai");
        System.out.println("helloReply = " + helloReply);
        customHeaderClient.shutdown();
    }

}
